<template>
  <div class="versionCompare-container">
    <div class="blackhole-header">
      {{ defaultSource.nodeName }}
    </div>
    <div class="BlackHole-container" ref="blackHoleContainer"></div>
    <!-- 构建 -->
    <div class="member-icon" @click="handelOpenMember()">
      <icon-font type="icon-change-consulta" />
    </div>
    <!-- 属性 -->
    <div class="attribute-icon" @click="handelOpenAttribute()">
      <icon-font type="icon-tishi" />
    </div>
    <!-- 构件详情 -->
    <versionMemberDrawer
      :key="versionMemberDrawer.key"
      :visible.sync="versionMemberDrawer.visible"
      @onSelect="componentOnSelect($event)"
    ></versionMemberDrawer>
    <!-- 属性信息 -->
    <versionAttributeDrawer
      ref="versionAttributeDrawer"
      :key="versionAttributeDrawer.key"
      :visible.sync="versionAttributeDrawer.visible"
    ></versionAttributeDrawer>
  </div>
</template>

<script>
//版本对比-预览模型
import { axios } from "@/utils/request";
import { canvasHolder } from "@/blackHoleTools/CanvasHolder";
import { releaseEngine, initialSDKModule } from "@/blackHoleTools/Engine";
import { mapGetters } from "vuex";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
//构件详情
import versionMemberDrawer from "./components/versionMemberDrawer.vue";
//属性信息
import versionAttributeDrawer from "./components/versionAttributeDrawer.vue";
export default {
  components: {
    versionMemberDrawer,
    versionAttributeDrawer,
    IconFont,
  },
  provide() {
    return {
      currentSoucre: () => this.defaultSource,
      currentData: () => this.defaultData,
      currentProbeRet: () => this.probeRet,
    };
  },
  data() {
    return {
      //构件列表
      versionMemberDrawer: {
        visible: false,
        key: "member",
      },
      //属性列表
      versionAttributeDrawer: {
        visible: false,
        key: "attribute",
      },
      defaultSource: {},
      defaultData: [],
      viewData: {},
      probeRet: {},
    };
  },
  computed: {
    ...mapGetters(["blackHoleAssetsPreFetch", "blackHoleRESystemCreated"]),
  },
  watch: {
    //系统引擎创建完成 && 公共资源加载完成
    // RESystemRenderReady: {
    //   handler(val) {
    //     if (val == true) {
    //       let { data } = this.$route.query;
    //       this.defaultSource = JSON.parse(data);
    //       document.title = this.defaultSource.nodeName;
    //       this.getData();
    //     }
    //   },
    //   immediate: true,
    // },

    blackHoleAssetsPreFetch: {
      handler(val) {
        this.$nextTick((_) => {
          if (val) {
            initialSDKModule();
          }
        });
      },
      immediate: true,
    },

    blackHoleRESystemCreated: {
      handler(val) {
        if (val) {
          this.$nextTick((_) => {
            let { data } = this.$route.query;
            this.defaultSource = JSON.parse(data);
            document.title = this.defaultSource.nodeName;
            this.getData();
          });
        }
      },
    },
  },
  created() {},
  methods: {
    getData() {
      Promise.all([this.getOverviewData(), this.getSetModelData()]).finally(
        (_) => {
          this.versionMemberDrawer.visible = true;
          this.versionAttributeDrawer.visible = true;
        }
      );
    },

    //点击左侧构件树
    componentOnSelect(ev) {
      let { dataSetId } = this;
      if (dataSetId) {
        try {
          this.allReset();
          let locIDList = [{ dataSetId, elemIdList: [ev] }];
          let backDepth = 0.5;
          BlackHole3D.Camera.setCamLocateToElem(locIDList, backDepth);
          this.updateElemColor([ev]);
        } catch (error) {}
      }
    },

    //改变构件颜色
    updateElemColor(elemList = []) {
      let { dataSetId } = this;
      try {
        let elemAttr = new BlackHole3D.REElemAttr();
        elemAttr.dataSetId = dataSetId;
        elemAttr.elemIdList = [32];
        console.log(elemList);
        elemAttr.elemClr = new BlackHole3D.REColor(255, 255, 0, -1);
        BlackHole3D.BIM.setElemAttr(elemAttr);
      } catch (error) {}
    },

    // 所有构件恢复初始状态
    allReset() {
      try {
        BlackHole3D.BIM.resetElemAttr("res_jifang", []);
      } catch (error) {}
    },

    //系统引擎创建完成回调【加载模型资源】
    onEngineCreated() {
      let { viewData } = this;
      let { fromVersion, toVersion } = this.defaultSource;
      let dom = this.$refs.blackHoleContainer;
      let BlackHole3D = window.BlackHole3D;
      canvasHolder.moveCanvasToTarget(this.$refs.blackHoleContainer);
      BlackHole3D.m_re_em_window_width = dom.clientWidth;
      BlackHole3D.m_re_em_window_height = dom.clientHeight;
      BlackHole3D.Coordinate.setEngineWorldCRS("EPSG:3857");
      let dataSetSources = [];
      let { dataSetId } = viewData?.[0] ?? {};
      this.dataSetId = dataSetId;
      viewData.forEach((item) => {
        let { dataSetId, resourcesAddress } = item;
        dataSetSources.push({
          dataSetId,
          resourcesAddress,
          useTransInfo: true,
          transInfo: [
            [1, 1, 1],
            [0, 0, 0, 1],
            [0, 0, 0],
          ],
          //指定第一个版本号
          useAssginVer: true,
          assginVer: fromVersion - 1,
          //指定第二个版本号
          useAssginVer2: true,
          assginVer2: toVersion - 1,
        });
      });
      //开始加载一个或多个模型资源
      BlackHole3D.Model.loadDataSet(dataSetSources);
    },

    //查询构建详情
    getOverviewData() {
      return new Promise((resolve, reject) => {
        let { token, dataSetId, fromVersion, toVersion } = this.defaultSource;
        axios
          .post(
            `/probusiness/blackHole3D/project/versionContrast/overview`,
            {
              dataSetId,
              fromVersion,
              toVersion,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.defaultData = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.defaultData = [];
            reject();
          });
      });
    },

    //查询BIM地址
    getSetModelData() {
      return new Promise((resolve, reject) => {
        let { token, dataSetId } = this.defaultSource;
        axios
          .post(
            `/probusiness/blackHole3D/project/dataSet/viewDataSetModel`,
            {
              dataSetIds: [dataSetId],
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.viewData = res?.data?.modelData ?? [];
            this.addEventListener();
            this.onEngineCreated();
            resolve();
          })
          .catch((_) => {
            this.viewData = [];
            reject();
          });
      });
    },

    //bim事件监听
    addEventListener() {
      //场景模型加载完成回调
      document.addEventListener("REDataSetLoadFinish", (_) => {
        //设置系统UI
        this.setSystemUI();
        //分屏展示不同版本
        //为了解决键盘事件的冲突
        BlackHole3D.canvas.focus();
        //分屏展示不同版本的模型
        BlackHole3D.setViewMode(
          BlackHole3D.REVpTypeEm.BIM,
          BlackHole3D.REVpTypeEm.BIM,
          BlackHole3D.REVpRankEm.LR
        );
      });
      window.addEventListener("resize", this.onResize);
      //鼠标探测模型事件
      document.addEventListener("RESystemSelElement", (e) => {
        var ProbeRet = BlackHole3D.Probe.getCurProbeRet();
        this.probeRet = ProbeRet;
        this.constructClick(e);
      });
    },

    //模型点击事件
    constructClick(e) {
      this.$refs.versionAttributeDrawer.getData();
    },

    //设置系统UI
    setSystemUI() {
      try {
        BlackHole3D.Graphics.setGeoCoordVisible(false);
        BlackHole3D.Graphics.setSysUIPanelVisible(true);
        BlackHole3D.Graphics.setSysPanelUIDockArea(3);
        BlackHole3D.Camera.resetCamLocate();
        BlackHole3D.Camera.resetCamBound();
      } catch (error) {}
    },

    //监听窗口尺寸变化
    onResize() {
      let box = this.$refs["blackHoleContainer"];
      if (box) {
        window.BlackHole3D.m_re_em_window_width = window.innerWidth;
        window.BlackHole3D.m_re_em_window_height = window.innerHeight;
      }
    },

    handelOpenMember() {
      this.versionMemberDrawer.visible = true;
      this.versionMemberDrawer.key = Date.now();
    },

    handelOpenAttribute() {
      this.versionAttributeDrawer.visible = true;
      this.versionAttributeDrawer.key = Date.now();
    },
  },
  beforeDestroy() {
    releaseEngine();
  },
};
</script>

<style lang="less" scoped>
.versionCompare-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  .blackhole-header {
    padding: 0 20px;
    line-height: 60px;
    font-size: 20px;
    font-weight: 400;
    color: #ffffff;
    background-color: #2f2f2f;
    flex-shrink: 0;
  }
  .BlackHole-container {
    flex: 1;
    text-align: center;
    width: 100%;
    height: 100%;
  }
  .member-icon {
    position: absolute;
    top: 80px;
    left: 10px;
    border: 1px solid #f6fbff;
    background: hsla(0, 0%, 100%, 0.8);
    border-radius: 4px;
    padding: 5px 10px;
    cursor: pointer;
    .anticon {
      font-size: 24px;
      color: #077ffe;
    }
  }
  .attribute-icon {
    position: absolute;
    top: 80px;
    right: 10px;
    border: 1px solid #f6fbff;
    background: hsla(0, 0%, 100%, 0.8);
    border-radius: 4px;
    padding: 5px 10px;
    cursor: pointer;
    .anticon {
      font-size: 24px;
      color: #077ffe;
    }
  }
}
</style>
